package com.im.project.webSocket;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSON;
import com.im.common.constant.Constant;
import com.im.common.enums.WsEnum;
import com.im.common.util.SpringContextHolder;
import com.im.project.entity.vo.MessageVo;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * 处理消息的handler(TextWebSocketFrame：在netty中是用于为websocket专门处理文本的对象frame是消息的载体)
 *
 * @author yunZhouJiaDi
 */
@Slf4j
public class WebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    @Resource
    private StpUtil stpUtil;

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        log.info("有新的连接加入。。。");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        log.info("有连接已经断开。。。");
        UserChannelCtxMap.removeContext(ctx.channel());
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame frame) {
        Channel channel = ctx.channel();
        Attribute<String> attribute = channel.attr(AttributeKey.valueOf(channel.id().toString()));
        String userId = attribute.get();
        RedisTemplate redisTemplate = SpringContextHolder.getBean("redisTemplate");
        redisTemplate.opsForValue().set(Constant.RedisConstant.USER_HEART_BEAT + userId, System.currentTimeMillis(), 6L, TimeUnit.SECONDS);
    }

    /**
     * 用于处理用户自定义的事件,当有用户事件触发时会调用此方法，例如连接超时，异常等。
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
        if (evt instanceof WebSocketServerProtocolHandler.HandshakeComplete) {
            WebSocketServerProtocolHandler.HandshakeComplete complete = (WebSocketServerProtocolHandler.HandshakeComplete) evt;
            String url = complete.requestUri();
            String token = getToken(url);
            if (token == null) {
                ctx.channel().close();
                return;
            }
            String userId = String.valueOf(stpUtil.getLoginIdByToken(token));
            if (userId.equals("null")) {
                ctx.channel().close();
                return;
            }
            log.info("用户{}登录ws成功", userId);
            Channel channel = UserChannelCtxMap.getContext(userId);
            if (channel != null && !ctx.channel().id().equals(channel.id())) {
                MessageVo messageVo = new MessageVo<>().
                        setCommandCode(WsEnum.FORCE_LOGOUT.getCode()).
                        setCommandName(WsEnum.FORCE_LOGOUT.getMessage()).
                        setContactId(userId).
                        setData(null);
                channel.writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(messageVo)));
                UserChannelCtxMap.closeContext(userId);
                UserChannelCtxMap.addContext(userId, ctx.channel());
            }
            UserChannelCtxMap.addContext(userId, ctx.channel());
        }
    }

    private String getToken(String url) {
        if (url.indexOf("?") == -1) {
            return null;
        }
        String[] queryParams = url.split("\\?");
        if (queryParams.length < 2) {
            return url;
        }
        String[] params = queryParams[1].split("=");
        if (params.length != 2) {
            return url;
        }
        return params[1];
    }

}
